// Fill out your copyright notice in the Description page of Project Settings.


#include "NetworkController.h"

#include "NetworkProjectGameMode.h"
#include "OnlineSubsystemUtils.h"
#include "GameFramework/PlayerState.h"
#include "Interfaces/OnlineSessionInterface.h"

void ANetworkController::ClientStartOnlineGame_Implementation()
{
	if (PlayerState)
	{
		IOnlineSubsystem* SubSystem = Online::GetSubsystem(GetWorld());
		if (SubSystem)
		{
			IOnlineSessionPtr SessionPtr = SubSystem->GetSessionInterface();
			if (SessionPtr.IsValid() && SessionPtr->GetNamedSession(PlayerState->SessionName) != nullptr)
			{
				SessionPtr->StartSession(PlayerState->SessionName);
			}
		}
	} else
	{
		GetWorld()->GetTimerManager().SetTimer(TimerHandle_ClientStartOnlineGame, this, &ANetworkController::ClientStartOnlineGame_Implementation, 0.2, false);
	}
}

void ANetworkController::ClientEndOnlineGame_Implementation()
{
	if (PlayerState)
	{
		IOnlineSubsystem* SubSystem = Online::GetSubsystem(GetWorld());
		if (SubSystem)
		{
			IOnlineSessionPtr SessionPtr = SubSystem->GetSessionInterface();
			if (SessionPtr.IsValid() && SessionPtr->GetNamedSession(PlayerState->SessionName) != nullptr)
			{
				SessionPtr->EndSession(PlayerState->SessionName);
			}
		}
	}
}

ANetworkController::ANetworkController()
{
	ChartType = FName("AllChart");
}

void ANetworkController::Say(FString Message)
{
	ServerSay(Message);
}

void ANetworkController::ServerSay_Implementation(const FString& Message)
{
	GetWorld()->GetAuthGameMode<ANetworkProjectGameMode>()->Broadcast(this, Message, ChartType);
}

bool ANetworkController::ServerSay_Validate(const FString& Msg)
{
	return true;
}

void ANetworkController::ClientTeamMessage_Implementation(APlayerState* SenderPlayerState, const FString& S, FName Type, float MsgLifeTime)
{
	OnReceiveMessage().Broadcast(SenderPlayerState, S, Type, MsgLifeTime);
	if (Type == ChartType)
	{
		if (GEngine)
		{
			GEngine->AddOnScreenDebugMessage(-1, 20.f, FColor::Green, S);
		}
	}
}
